"""
set timeout
"""
from threading import Thread


class TimeoutException(Exception):
    pass


def timelimited(timeout):
    def decorator(function):
        def decorator2(*args, **kwargs):
            class TimeLimited(Thread):
                def __init__(self, _error=None, ):
                    Thread.__init__(self)
                    self._error = _error

                def run(self):
                    try:
                        self.result = function(*args, **kwargs)
                    except Exception as e:
                        self._error = str(e)

            t = TimeLimited()
            t.start()
            t.join(timeout)

            if t._error is None:
                return t.result

        return decorator2

    return decorator
